package api

import (
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"net/http"
	"strconv"
	"web_end/forms"
	"web_end/global/response"
	"web_end/proto"
	"web_end/utils"
)

func HandlerGroupResponse(raw *proto.GroupResponseInfo) *response.GroupResponse {
	return &response.GroupResponse{
		GroupId:        raw.Id,
		LeaderId:       raw.LeaderId,
		Name:           raw.Name,
		Desc:           raw.Desc,
		Cover:          raw.Cover,
		InvitationCode: raw.InvitationCode,
	}
}

// CreateGroup /* 创建团队
func CreateGroup(ctx *gin.Context) {
	var createGroupForm forms.CreateGroupForm
	if err := ctx.ShouldBindJSON(&createGroupForm); err != nil {
		ctx.JSON(http.StatusOK, gin.H{
			"code": response.CodeBadRequest,
			"msg":  response.MsgParamsError,
		})
		return
	}

	userServerClient := *utils.CreateUserServerGrpc("GetUserById", "查找用户")
	_, err := userServerClient.GetUserById(ctx, &proto.IdRequest{
		UserId: createGroupForm.LeaderId,
	})
	if err != nil {
		zap.S().Errorw("[GetUserById] 查询 [用户] 失败")
		utils.HandleGrpcErrorToHttp(err, ctx)
		return
	}

	projectServerClient := *utils.CreateProjectGrpc("CreateGroup", "创建团队")
	rsp, err := projectServerClient.CreateGroup(ctx, &proto.CreateGroupInfo{
		Name:     createGroupForm.Name,
		Desc:     createGroupForm.Desc,
		Cover:    createGroupForm.Cover,
		LeaderId: createGroupForm.LeaderId,
	})
	if err != nil {
		zap.S().Errorw("[CreateGroup] 创建 [团队] 失败")
		utils.HandleGrpcErrorToHttp(err, ctx)
		return
	}

	ctx.JSON(http.StatusOK, gin.H{
		"code": response.CodeOk,
		"msg":  response.MsgSuccess,
		"data": HandlerGroupResponse(rsp),
	})
}

// GetGroupById /* 通过团队ID查询团队
func GetGroupById(ctx *gin.Context) {
	groupIdStr := ctx.Param("id")
	groupIdInt, _ := strconv.Atoi(groupIdStr)

	projectServerClient := *utils.CreateProjectGrpc("GetGroupById", "通过ID查询团队")
	rsp, err := projectServerClient.GetGroupById(ctx, &proto.GroupIdInfo{
		Id: uint64(groupIdInt),
	})
	if err != nil {
		if err != nil {
			zap.S().Errorw("[GetGroupById] 查询 [团队] 失败")
			utils.HandleGrpcErrorToHttp(err, ctx)
			return
		}
	}

	data := HandlerGroupResponse(rsp)
	ctx.JSON(http.StatusOK, gin.H{
		"code": response.CodeOk,
		"msg":  response.MsgSuccess,
		"data": data,
	})
}

// GetGroupByName /* 通过团队名称查询团队
func GetGroupByName(ctx *gin.Context) {
	groupName := ctx.Param("name")

	projectServerClient := *utils.CreateProjectGrpc("GetGroupByName", "通过名称查询团队")
	rsp, err := projectServerClient.GetGroupByName(ctx, &proto.GroupNameInfo{
		Name: groupName,
	})
	if err != nil {
		zap.S().Errorw("[GetGroupByName] 查询 [团队] 失败")
		utils.HandleGrpcErrorToHttp(err, ctx)
		return
	}

	data := HandlerGroupResponse(rsp)
	ctx.JSON(http.StatusOK, gin.H{
		"code": response.CodeOk,
		"msg":  response.MsgSuccess,
		"data": data,
	})
}

// UpdateGroup /* 更新团队
func UpdateGroup(ctx *gin.Context) {
	var updateGroupForm forms.UpdateGroupForm
	if err := ctx.ShouldBindJSON(&updateGroupForm); err != nil {
		ctx.JSON(http.StatusOK, gin.H{
			"code": response.CodeBadRequest,
			"msg":  response.MsgParamsError,
		})
		return
	}

	userServerClient := *utils.CreateUserServerGrpc("GetUserById", "查询用户")
	_, err := userServerClient.GetUserById(ctx, &proto.IdRequest{
		UserId: updateGroupForm.LeaderId,
	})
	if err != nil {
		zap.S().Errorw("[UpdateGroup] 查询 [用户] 失败")
		utils.HandleGrpcErrorToHttp(err, ctx)
		return
	}

	projectServerClient := *utils.CreateProjectGrpc("UpdateGroup", "更新团队")
	_, err = projectServerClient.UpdateGroup(ctx, &proto.UpdateGroupInfo{
		Name:     updateGroupForm.Name,
		Desc:     updateGroupForm.Desc,
		Cover:    updateGroupForm.Cover,
		Id:       updateGroupForm.GroupId,
		LeaderId: updateGroupForm.LeaderId,
	})
	if err != nil {
		zap.S().Errorw("[UpdateGroup] 更新 [团队] 失败")
		utils.HandleGrpcErrorToHttp(err, ctx)
		return
	}

	ctx.JSON(http.StatusOK, gin.H{
		"code": response.CodeOk,
		"msg":  response.MsgSuccess,
	})
}

// DeleteGroup /* 删除团队
func DeleteGroup(ctx *gin.Context) {
	var deleteGroupForm forms.DeleteGroupForm
	if err := ctx.ShouldBindJSON(&deleteGroupForm); err != nil {
		ctx.JSON(http.StatusOK, gin.H{
			"code": response.CodeBadRequest,
			"msg":  response.MsgParamsError,
		})
		return
	}

	projectServerClient := *utils.CreateProjectGrpc("DeleteGroup", "删除团队")
	_, err := projectServerClient.DeleteGroup(ctx, &proto.DeleteGroupInfo{
		Id:       deleteGroupForm.GroupId,
		LeaderId: deleteGroupForm.LeaderId,
	})
	if err != nil {
		zap.S().Errorw("[DeleteGroup] 删除 [团队] 失败")
		utils.HandleGrpcErrorToHttp(err, ctx)
		return
	}

	ctx.JSON(http.StatusOK, gin.H{
		"code": response.CodeOk,
		"msg":  response.MsgSuccess,
	})
}

// JoinGroup /* 加入团队
func JoinGroup(ctx *gin.Context) {
	var joinMemberForm forms.JoinMemberForm
	if err := ctx.ShouldBindJSON(&joinMemberForm); err != nil {
		ctx.JSON(http.StatusOK, gin.H{
			"code": response.CodeBadRequest,
			"msg":  response.MsgParamsError,
		})
		return
	}

	userServerClient := *utils.CreateUserServerGrpc("GetUserById", "查询用户")
	_, err := userServerClient.GetUserById(ctx, &proto.IdRequest{
		UserId: joinMemberForm.UserId,
	})
	if err != nil {
		zap.S().Errorw("[JoinGroup] 查询 [用户] 失败")
		utils.HandleGrpcErrorToHttp(err, ctx)
		return
	}

	projectServerClient := *utils.CreateProjectGrpc("JoinGroup", "加入团队")
	rsp, err := projectServerClient.GetGroupById(ctx, &proto.GroupIdInfo{
		Id: joinMemberForm.GroupId,
	})
	if err != nil {
		zap.S().Errorw("[GetGroupById] 查询 [团队] 失败")
		utils.HandleGrpcErrorToHttp(err, ctx)
		return
	}
	if rsp.InvitationCode != joinMemberForm.InvitationCode {
		ctx.JSON(http.StatusOK, gin.H{
			"code": response.CodeBadRequest,
			"msg":  response.MsgParamsError,
		})
		return
	}

	_, err = projectServerClient.JoinGroup(ctx, &proto.GroupMemberInfo{
		GroupId: joinMemberForm.GroupId,
		UserId:  joinMemberForm.UserId,
	})
	if err != nil {
		zap.S().Errorw("[JoinGroup] 加入 [团队] 失败")
		utils.HandleGrpcErrorToHttp(err, ctx)
		return
	}

	ctx.JSON(http.StatusOK, gin.H{
		"code": response.CodeOk,
		"msg":  response.MsgSuccess,
	})
}

// ExitGroup /* 离开团队
func ExitGroup(ctx *gin.Context) {
	var groupMemberInfo forms.ExitMemberForm
	if err := ctx.ShouldBindJSON(&groupMemberInfo); err != nil {
		ctx.JSON(http.StatusOK, gin.H{
			"code": response.CodeBadRequest,
			"msg":  response.MsgParamsError,
		})
		return
	}

	userServerClient := *utils.CreateUserServerGrpc("GetUserById", "离开团队")
	_, err := userServerClient.GetUserById(ctx, &proto.IdRequest{
		UserId: groupMemberInfo.UserId,
	})
	if err != nil {
		zap.S().Errorw("[GetUserById] 查询 [用户] 失败")
		utils.HandleGrpcErrorToHttp(err, ctx)
		return
	}

	projectServerClient := *utils.CreateProjectGrpc("ExitGroup", "离开团队")
	_, err = projectServerClient.ExitGroup(ctx, &proto.GroupMemberInfo{
		GroupId: groupMemberInfo.GroupId,
		UserId:  groupMemberInfo.UserId,
	})
	if err != nil {
		zap.S().Errorw("[DeleteGroup] 离开 [团队] 失败")
		utils.HandleGrpcErrorToHttp(err, ctx)
		return
	}

	ctx.JSON(http.StatusOK, gin.H{
		"code": response.CodeOk,
		"msg":  response.MsgSuccess,
	})
}

// GetMemberList /* 获取团队成员列表
func GetMemberList(ctx *gin.Context) {
	groupIdStr := ctx.Param("id")
	groupIdInt, _ := strconv.Atoi(groupIdStr)

	projectServerClient := *utils.CreateProjectGrpc("GetMemberList", "查询成员列表")
	rsp, err := projectServerClient.GetMemberList(ctx, &proto.GroupIdInfo{
		Id: uint64(groupIdInt),
	})
	if err != nil {
		zap.S().Errorw("[GetMemberList] 查询 [成员] 失败")
		utils.HandleGrpcErrorToHttp(err, ctx)
		return
	}

	// 处理成员
	userServerClient := *utils.CreateUserServerGrpc("GetUserById", "查询成员列表")
	var userList []response.UserResponse
	for _, user := range rsp.MemberList {
		userRsp, err := userServerClient.GetUserById(ctx, &proto.IdRequest{
			UserId: user.UserId,
		})
		if err != nil {
			zap.S().Errorw("[GetUserById] 查询 [用户] 失败")
			utils.HandleGrpcErrorToHttp(err, ctx)
			return
		}
		userList = append(userList, *HandleUserResponse(userRsp))
	}
	data := map[string]interface{}{
		"groupId":    rsp.GroupId,
		"memberList": userList,
	}
	ctx.JSON(http.StatusOK, gin.H{
		"code": response.CodeOk,
		"msg":  response.MsgSuccess,
		"data": data,
	})
}
